package com.wf.course.service.impl;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.utils.page.PageBean;
import com.wf.course.service.IIndexTypeService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;
import com.wf.course.dao.IIndexTypeMapper;
import com.wf.course.model.ad.IndexType;

@Service
@Transactional(rollbackFor=Exception.class)
public class IIndexTypeServiceImpl implements IIndexTypeService{
	
	@Autowired
	private IIndexTypeMapper mapper;

	@Override
	public void indexInfo(PageBean<IndexType> pageBean) {
		// TODO Auto-generated method stub
		pageBean.setResults(this.mapper.queryList(pageBean));
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean));
		
	}

	@Override
	public void saveOrUpdateIndexType(IndexType indexType,MultipartFile imgFile) {
		// TODO Auto-generated method stub
		
		//新增
		if (indexType.getIndexTypeCode() == null) {
			if (!imgFile.isEmpty()) {
				String imgUrl = "";
				try {
					imgUrl = OSSUtil.addFile(imgFile, "adInfo", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				indexType.setIcon(imgUrl);
			}
			this.mapper.saveIndexType(indexType);
		//修改
		} else {

			if (imgFile.getSize() != 0) {
				IndexType ity = mapper.queryIndexTypeById(indexType.getIndexTypeCode());
				try{
					if(StringUtils.isNotBlank(ity.getIcon())){
						// 删除原来图片
						OSSUtil.delete(ity.getIcon(), Constants.IGM_BUCKET);
					}
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				// 重新上传
				// 上传
				String imgUrl = "";
				try {
					imgUrl = OSSUtil.addFile(imgFile, "adInfo", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				indexType.setIcon(imgUrl);
			}
		
			this.mapper.updateIndexType(indexType);
		}
		
	 
 }

	@Override
	public IndexType queryIndexTypeById(Integer id) {
		// TODO Auto-generated method stub
		return mapper.queryIndexTypeById(id);
	}

	@Override
	public void deleteById(Integer indexTypeCode) {
		// TODO Auto-generated method stub
		this.mapper.deleteById(indexTypeCode);
		 
	}
 
	@Override
	public List<IndexType> queryTypes(){
		return this.mapper.queryTypes();
	}
	
}
